#-*- coding: UTF-8 -*- 
import cv2
import time
import socket
import nanocamera as nano
import os
import numpy as np
import glob
import pickle
from map2array_lib import map2array , array2senddata
from neural_net_classify.conv_net import ConvNet
from uart_example import get_uart_data
from utils import *
import serial

# 服务端ip地址
HOST = '192.168.1.136'
# 服务端端口号
PORT = 8080
ADDRESS = (HOST, PORT)
width=1280
height=720

serial_port = serial.Serial(
    port="/dev/ttyTHS1",
    baudrate=115200,
    bytesize=serial.EIGHTBITS,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
)
ttt=my_timer() 
# 创建一个套接字
tcpClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接远程ip
tcpClient.connect(ADDRESS)

with open('mtx.pickle',"rb") as f1:
    mtx = pickle.load(f1)
with open('dist.pickle',"rb") as f1:
    dist = pickle.load(f1)

h,  w = height,width 
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))

# undistort
mapx, mapy = cv2.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5)
def ten2byteofhex(num):
    hex_str=str(hex(num))[2:]
    if len(hex_str)==1:
        hex_str='0'+hex_str
    return(bytes.fromhex(hex_str))

treasure_dict={0:"blue_yellow",1:"blue_green",2:"red_yellow",3:"red_green"}
testnet=ConvNet()
testnet.load_params("./neural_net_classify/out1.pkl")

camera = nano.Camera(flip=0, width=width, height=height, fps=10)
for i in range(5):
    cv_image=camera.read()
while True:
    try:
        num=len(os.listdir("./shot"))
        # 读取图像
        cv_image = camera.read()
        
        dst = cv2.remap(cv_image, mapx, mapy, cv2.INTER_LINEAR)
        # crop the image
        x, y, w, h = roi
        cv_image = dst[y:y+h, x:x+w]

        if len(os.listdir("./shot/shot_flag"))==1:
            cv2.imwrite("./shot/"+str(num-1)+".png",cv_image)
            os.remove("/home/xd233/gd_code/shot/shot_flag/1")
            print(str(num-1)+".png is saved")
        #x_record=im2coordinate(cv_image)
       # cv2.circle(cv_image,(x_record,615),5,(213,0,0),-1)
        crop_treasure, [y_min, y_max, x_min, x_max] = crop_treasure_picture(cv_image)
        if crop_treasure is not None:
            print(str(int((x_min+x_max)/2/1025*384)),y_min)
            if crop_treasure[0][0][0].dtype=='uint8':
                crop_treasure=crop_treasure/255
            input_img = cv2.resize(crop_treasure, (30, 60))
            input_img=np.expand_dims(input_img,axis=0)
            input_img=input_img.transpose(0,3,1,2)
            out=testnet.predict(input_img,train_flg=False)
            obj_num=np.argmax(out)
            if cv_image[0][0][0].dtype!='uint8':
                cv_image=cv_image*255
                cv_image=cv_image.astype("uint8")
            cv2.putText(cv_image, treasure_dict[obj_num], (x_min, y_min-10),cv2.FONT_HERSHEY_SIMPLEX, 1, (250,100,0), 2)
            cv2.rectangle(cv_image, (x_min, y_min),(x_max,y_max)
                          , (0, 0, 255), 2)
        else:
            print("no object detected")
        #ttt.toc()
        cv_image=cv2.resize(cv_image,(int(1280//3.5),int(720//3.5)))
        # 压缩图像
        img_encode = cv2.imencode('.jpg', cv_image, [cv2.IMWRITE_JPEG_QUALITY, 99])[1]
        # 转换为字节流
        bytedata = img_encode.tostring()
        # 标志数据，包括待发送的字节流长度等数据，用‘,’隔开
        flag_data = (str(len(bytedata))).encode() + ",".encode() + " ".encode()

        tcpClient.send(flag_data)
        # 接收服务端的应答
        data = tcpClient.recv(1024)
        if ("ok" == data.decode()):
            # 服务端已经收到标志数据，开始发送图像字节流数据
            tcpClient.send(bytedata)
        # 接收服务端的应答
        data = tcpClient.recv(1024)
        if ("ok" == data.decode()):
            pass

            # 计算发送完成的延时
           # print("延时：" + str(int((time.perf_counter() - start) * 1000)) + "ms")
    except KeyboardInterrupt:
        print("key board")
        break
    except:
        print("something is error,try again")
